package com.konke.smartpad_huahao.domain;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import com.konke.smartpad_huahao.MyApplication;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.base.Request;
import com.zsj.comminlibrary.util.FileUtil;
import com.zsj.comminlibrary.util.UIUtils;
import com.zsj.comminlibrary.view.dialog.LoadingDialog;

import java.io.File;

import androidx.core.content.FileProvider;

/**
 * APP 更新工具类
 */
public abstract class UpdateUtils {

    private static final String TAG = UpdateUtils.class.getSimpleName();

    private static LoadingDialog customDialog;


    public static void UpApp(final Activity activity, final String url) {

        Log.i(TAG, "下载:" + url);
        OkGo.<File>get(url).execute(new FileCallback(FileUtil.getDownloadDir(), "Pda.apk") {
            @Override
            public void onSuccess(com.lzy.okgo.model.Response<File> response) {
                Log.i(TAG, "下载成功");
                customDialog.dismiss();

                Intent intent = new Intent(Intent.ACTION_VIEW);
                // 由于没有在Activity环境下启动Activity,设置下面的标签
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
                    //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                    Uri apkUri = FileProvider.getUriForFile(MyApplication.getContext(), "com.konke.smartpad_huahao.fileProvider", response.body());
                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                } else {
                    intent.setDataAndType(Uri.fromFile(response.body()),
                            "application/vnd.android.package-archive");
                }
                activity.startActivity(intent);

            }

            @Override
            public void onStart(Request<File, ? extends Request> request) {
                super.onStart(request);
                //开始下载
                Log.i(TAG, "开始下载：");

                customDialog = new LoadingDialog.Builder(activity).setLoading("正在下载").build();
                customDialog.show();
            }

            @Override
            public void downloadProgress(Progress progress) {

                String s = "" + progress.fraction;
                Log.i(TAG, "下载进度：" + s);

            }

            @Override
            public void onError(com.lzy.okgo.model.Response<File> response) {
                Log.i(TAG, "下载失败");
                UIUtils.showToast("下载失败");
                customDialog.dismiss();
            }
        });


    }


}
